package  com.tjc.cloud.util.http.status

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.validation.BindException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestControllerAdvice


@RestControllerAdvice
open class HttpException(message:String?=null) :RuntimeException(message){
    val logger: Logger =LoggerFactory.getLogger(HttpException::class.java)


    class FOUND(message: String? = null) : HttpException(message)

    @ExceptionHandler(FOUND::class)
    @ResponseStatus(value = HttpStatus.FOUND, reason = "重定向")
    fun found(e: RuntimeException) = e.message ?: "重定向"


    class NOT_FOUND(message: String? = null) : HttpException(message)

    @ExceptionHandler(NOT_FOUND::class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "对象不存在")
    fun notFound(e: RuntimeException) = e.message ?: "对象不存在"

    class NOT_MODIFIED(message: String? = null) : HttpException(message)

    @ExceptionHandler(NOT_MODIFIED::class)
    @ResponseStatus(value = HttpStatus.NOT_MODIFIED, reason = "未修改")
    fun notModified(e: RuntimeException) = e.message ?: "未修改"

    class UNAUTHORIZED(message: String? = null) : HttpException(message)

    @ExceptionHandler(UNAUTHORIZED::class)
    @ResponseStatus(value = HttpStatus.UNAUTHORIZED, reason = "请求未经授权")
    fun unauthorized(e: RuntimeException) = e.message ?: "请求未经授权"

    class FORBIDDEN(message: String? = null) : HttpException(message)

    @ExceptionHandler(FORBIDDEN::class)
    @ResponseStatus(value = HttpStatus.FORBIDDEN, reason = "请求被拒绝")
    fun forbidden(e: RuntimeException) = e.message ?: "请求被拒绝"

    class CONFLICT(message: String? = null) : HttpException(message)

    @ExceptionHandler(CONFLICT::class)
    @ResponseStatus(value = HttpStatus.CONFLICT, reason = "请求冲突")
    fun conflict(e: RuntimeException) = e.message ?: "请求冲突"

    class TOO_MANY_REQUESTS(message: String? = null) : HttpException(message)

    @ExceptionHandler(TOO_MANY_REQUESTS::class)
    @ResponseStatus(value = HttpStatus.TOO_MANY_REQUESTS, reason = "请求过于频繁")
    fun tooManyRequests(e: RuntimeException) = e.message ?: "请求过于频繁"

    class BAD_REQUEST(message: String? = null) : HttpException(message)

    @ExceptionHandler(BAD_REQUEST::class, BindException ::class)
    @ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "错误的请求")
    fun bad_Request(e: RuntimeException) = e.message ?: "错误的请求"



    @ExceptionHandler(Exception::class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR, reason = "服务器内部错误")
    fun internal_server_error(e: RuntimeException): String {
        logger.error(e.message,e)
        return e.message ?: "服务器内部错误"
    }
}
